<template>
  <div style="background-color:#f7f8fa;">
    <van-nav-bar ref="VanNavBarDmo" fixed left-arrow ri-text="返回" style="z-index:999"
                 title="信息填写"
                 @click-left="onClickLeft"/>
    <van-overlay :show="loading">
      <div class="loading">
        <van-loading color="#0094ff" style="z-index:999"/>
      </div>
    </van-overlay>
    <van-form scroll-to-error @submit="onFailed">
      <van-tabs v-model:active="active" scrollspy sticky type="line">
        <template #nav-bottom>
          <!-- <div>
            <van-icon name="down" />
          </div> -->
        </template>
        <van-tab v-for="item in activeList" :title="item.title" :title-style="`color: ${item.color}`">
          <div class="module">
            <FromList :FromArr="fromScreen[item.key]" :froKey="item.key" :title="item.title" label-width="7.5rem"
                      @blur="item.blur"/>
          </div>
        </van-tab>
      </van-tabs>
      <div style="margin: 16px;background-color: #fff;">
        <van-row>
          <van-col span="12" style="padding:0 10px">
            <van-button :disabled="buttonReslt || +CounterStore.isSubmit === 1" block round type="primary"
                        @click="save">
              保存
            </van-button>
          </van-col>
          <van-col span="12" style="padding:0 10px">
            <van-button :disabled="buttonReslt || +CounterStore.isSubmit === 1" block native-type="submit" round
                        type="primary">
              提交
            </van-button>
          </van-col>
        </van-row>
      </div>
    </van-form>
  </div>

</template>

<script setup>
import {
  contactWay,
  essentialInformation,
  personalDetails,
  TheHouseholdRegistrationInformation,
  addressMessage,
  emergencyContact,
  memberFamily,
  occupationalHistory,
  IdCardRegularExpression,
  mailboxVerification
} from './queryStatus.js'
import {
  getBankName,
  insertEmployeeInfo,
  getAllEmployees,
  addSubmit,
  checkCard,
  getCardIdEmployeeInfo,
  addSynEmployeeInfo
} from '@/api/Fillln.js'
import FromList from './FromList.vue'
import {educationalInformation} from './educationalInformation'
import BlurArr from './Blur'
import {useCounterStore} from '@/pinia/user.js'
import {Toast, Dialog} from 'vant';
import {Base64} from 'js-base64'


// pinia  初始化
const CounterStore = useCounterStore()
// 每次进入界面的时候将这个界面设置为缓存页面
CounterStore.setIncludeList(['fillin'])
// 所有元素的值
const fromValueArr = reactive({})
//  vue  router 初始化
const Router = useRouter()
// vue route 初始化
const Route = useRoute()
// 获取query中的参数    base64解析
const query = JSON.parse(Base64.decode(Route.query.data))
//  页面上 所有的填写项
const fromScreen = reactive({})
// 页面加载前的loading
const loading = ref(null)
//  初始化 三要素
const ThirdWeNeedFactor = reactive({
  mobile: '', idcard: '', name: ''
})


//   初始化数据
async function init(a = {}) {
  // loading
  loading.value = true

  // 默认数据
  let res

  if (Object.keys(a).length === 0) {
    // 接口请求  请求保存过的信息
    res = await AllEmployees()
  } else {
    //   如果二次入职  会重新调用init 函数并且将需要同步的信息传过来
    res = a
    //  将同步的emlloyeeId存起来
    CounterStore.setOldEmployeeId(res.employeeId)
  }
  //  无论是通过那种方式获取填入默认信息  都不修改手机号码
  res.mobileNumber = CounterStore.mobile
  //  无论通过那种方式都不覆盖人员类型
  const b = CounterStore.HireType
  res.employeeType = b === 'regular' ? '正式工' : b === 'dispatched' ? '派遣工' : b === 'Hours' ? '小时工' : b === 'trainee' ? '实习生' : {}

  //  const a = +b === 1 ? 'regular' : +b === 2 ? 'dispatched' : +b === 3 ? 'Hours' : +b === 4 ? 'trainee' : ''
  if (res) {
    // 详细信息
    fromScreen.personalDetails = await personalDetails(res)
    // 身份信息
    fromScreen.essentialInformation = await essentialInformation(res)
    // 户籍信息
    fromScreen.TheHouseholdRegistrationInformation = await TheHouseholdRegistrationInformation(res)
    // 联系信息
    fromScreen.contactWay = await contactWay(res)
    // 地址信息
    fromScreen.addressMessage = await addressMessage(res)
    // 紧急联系人
    fromScreen.emergencyContact = await emergencyContact(res)
    // 家庭成员  memberFamily
    fromScreen.memberFamily = await memberFamily(res)
    // 工作经历
    fromScreen.occupationalHistory = await occupationalHistory(res)
    // 背景信息
    fromScreen.educationalInformation = await educationalInformation(res)
  }
  loading.value = false

}

// 获取保存的信息
async function AllEmployees() {
  const res = await getAllEmployees(CounterStore.mobile)
  if (res.success) {
    CounterStore.setEmployeeId(res.message.employeeId)
    CounterStore.setIsSubmit(res.message.isSubmit)
    res.message.isAttribution= CounterStore.isAttribution
    console.log(CounterStore.isAttribution)
    console.log(res.message)
    return res.message
  } else {
    Toast.fail('加载失败请联系管理员')
    return false
  }
}


// 根据当前的输入 情况改变当前title 的颜色
const setItem = function (it, activeItem) {
  if (it) {
    const itemArr = Object.keys(it)
    let a = 0
    // 排除这些
    const arr = ['birthDate', 1, '1']
    itemArr.forEach(item => {
      if (it[item] || arr.includes(item)) a += 1
    })
    if (a === itemArr.length) {
      activeItem.color = '#07c160'
    } else if (a > 0) {
      activeItem.color = '#ffd01e'
    } else {
      activeItem.color = '#000'
    }
  }
}

// 生命周期函数  当页面渲染完成后调用
onMounted(() => {
  init()
})

// 获取当前导航栏 Dmo
const VanNavBarDmo = ref(null)


// 返回上一个页面
const onClickLeft = () => {
  //返回上个界面的时候次页面不再进行缓存
  CounterStore.setIncludeList([])
  Router.push('/home')
}


// 提交
const onFailed = async function () {
  const sa = await save(1)
  if (sa) {
    const res = await addSubmit(CounterStore.employeeId)
    if (res.success) {
      Toast.success(res.message)
      setTimeout(function () {
        CounterStore.setIncludeList([])
        Router.push('./home')
      }, 2000)
    } else {
      Toast.fail(res.message)
    }
  }

}

// 保存
const save = async function (type) {
  if (!fromValueArr.data) {
    Toast.fail('请先填写或修改信息后保存')
    return false
  }
  const data = {}
  // 拿出所有文本框的值
  Object.keys(fromScreen).forEach(key => {
    fromScreen[key].forEach(i => {
      data[i.key] = i.value
    })
  })
  // 将发生变化的值 替换掉原始值
  fromValueArr.data = {...fromValueArr.data, ...data}
  // 判断是否是二次入职
  CardIdEmployeeInfo(fromValueArr.data.cardId)
  // 获取 家庭成员信息
  fromValueArr.data.family = familySetList()
  // 获取工作经历信息
  fromValueArr.data.history = historySetList()
  Toast.loading({
    message: '加载中...',
    forbidClick: true,
    loadingType: 'spinner',
  })
  fromValueArr.data.employeeId = CounterStore.employeeId
  // 如果是提交的话   校验   家庭成员  工作经历  是否填写完整
  if (type === 1) {
    //    对象需要判断的Kye
    const familyList = ['familyBirthDate', 'familyName', 'familyNameFirst', 'familyRelation', 'workPosition', 'workUnit']
    //    过滤所有的没有任何值的对象
    const familyArr = isObjBeEmpty(fromValueArr.data.family, familyList)
    fromValueArr.data.family = familyArr
    //     筛选否是存在没有填写完整的 家庭成员信息
    const isFamily = isVerify(familyArr, familyList)
    if (!isFamily) {
      Toast.fail('请填写完整家庭成员信息')
      return false
    }
    //    需要判断的key
    const historyList = ['departmentName', 'endDate', 'officeCompany', 'startDate', 'workPostName', 'workWitnessName']
    //    过滤所有的没有任何值的对象
    const historyArr = isObjBeEmpty(fromValueArr.data.history, historyList)
    fromValueArr.data.history = historyArr
    //    判断是否存在没有填写完整的工作经历
    const isHistory = isVerify(historyArr, historyList)
    if (!isHistory) {
      Toast.fail('请填写完整工作经历')
      return false
    }
  }
  const valueData = fromValueArr.data
  if ((valueData.emailAddress && !valueData.emailType) || (!valueData.emailAddress && valueData.emailType)) {
    Toast.fail("联系信息中的邮箱信息")
    return false
  }
  if (valueData.emailAddress) {
    const o = mailboxVerification(valueData.emailAddress)
    if (o === '邮箱格式不正确') {
      Toast.fail(o)
      return false
    }
  }
  const HireType = CounterStore.HireType
  if (type === 1 && (HireType === 'regular' || HireType === 'trainee')) {
    const idCardFiles = fromValueArr.data.idCardFiles
    const bankCardFiles = fromValueArr.data.bankCardFiles
    if (Array.isArray(idCardFiles) && idCardFiles.length < 2) {
      Toast.fail('请上传身份证正反面照片')
      return false
    }
    if (Array.isArray(bankCardFiles) && bankCardFiles.length < 2) {
      Toast.fail('请上传银行卡反面照片')
      return false
    }
  }

  const dataMessage = {...fromValueArr.data}
  dataMessage.idCardFiles = ''
  dataMessage.bankCardFiles = ''
  const res = await insertEmployeeInfo(dataMessage)
  if (res.success) {
    if (type === 1) return res.success
    Toast.success(res.message)
  } else {
    Toast.fail(res.message)
  }
}


function isObjBeEmpty(dataArr, arr) {
  return dataArr.filter(item => {
    let isDelete = true
    // 判断所有 需要判断的对象值 去掉空格后 是否为空  是否为空    不为空的的话转为字符串   去掉所有空格                             否则为 ''
    if (isDelete) isDelete = arr.some(it => (item[it] ? (item[it] + '')?.replace(/\s+/g, '') : '') !== '')
    if (isDelete) return item
  })
}

function isVerify(dataArr, arr) {
  let isFamily = true
  // 遍历处有没有不等于空的值   都为空的话 isFamily  === true  只要有一个不为空就返回false
  dataArr.forEach(item => {
    // 判断 所有需要判断的key
    if (isFamily) isFamily = !(arr.some(it => (item[it] ? (item[it] + '')?.replace(/\s+/g, '') : '') === ''))
  })
  return isFamily
}


// 将家庭成员重构成数组
function familySetList() {
  const family = []
  let number = 0
  const familyList = Object.keys(fromValueArr.memberFamily)
  const arr = ['familyBirthDate', 'familyName', 'familyNameFirst', 'workUnit', 'familyRelation', 'familyId', 'workPosition']
  familyList.forEach(item => {
    if (+item) number = number < item ? item : number
  })
  for (let i = 0; i < number; i++) {
    const obj = {}
    arr.forEach(item => {
      obj[`${item}`] = fromValueArr.data[`${item}${i ? 1 + i : ''}`]
    })
    const is = arr.some(item => (obj[item] + '')?.replace(/\s+/g, '') !== '')
    if (is) family.push(obj)
  }
  return family
}

// 工作经历重构成数组
function historySetList() {
  const history = []
  let number = 0
  const historyList = Object.keys(fromValueArr.occupationalHistory)
  const arr = ['startDate', 'endDate', 'officeCompany', 'departmentName', 'workPostName', 'workWitnessName', 'workId']
  historyList.forEach(item => {
    if (+item) number = number < item ? item : number
  })
  for (let i = 0; i < number; i++) {
    const obj = {}
    arr.forEach(item => {
      obj[`${item}`] = fromValueArr.data[`${item}${i ? 1 + i : ''}`] || ''
      delete fromValueArr.data[`${item}${i ? 1 + i : ''}`]
    })
    const is = arr.some(item => (obj[item] + '')?.replace(/\s+/g, '') !== '')
    if (is) history.push(obj)
  }
  return history
}

// let CardInfo

// 导航列表
const activeList = reactive([
  {
    active: 1, title: '身份信息', key: 'essentialInformation', color: '#000',
    blur: blurArr
  },
  {
    active: 2, title: '详细信息', key: 'personalDetails', color: '#000',
    blur: blurArr
  },
  {
    active: 3, title: '户籍信息', key: 'TheHouseholdRegistrationInformation', color: '#000',
    blur: blurArr
  },
  {
    active: 4, title: '联系信息', key: 'contactWay', color: '#000',
    blur: blurArr
  },
  {
    active: 5, title: '地址信息', key: 'addressMessage', color: '#000',
    blur: blurArr
  },
  {
    active: 6, title: '紧急联系人', key: 'emergencyContact', color: '#000',
    blur: blurArr
  },
  {
    active: 7, title: '家庭成员', key: 'memberFamily', color: '#000',
    blur: blurArr
  },
  {
    active: 8, title: '工作经历', key: 'occupationalHistory', color: '#000',
    blur: blurArr
  },
  {
    active: 9, title: '背景信息', key: 'educationalInformation', color: '#000',
    blur: blurArr
  }
])


// 三要素验证结果
// const buttonReslt = ref(true)
const buttonReslt = ref(false)


async function blurArr(fromValue, Arr, key) {
  BlurArr[`${key.value}Blur`]({fromValue, Arr, fromScreen, activeList, key})
  // 获取当前对象 this
  const activeItem = getItem(key.value)
  // 修改标题颜色
  if (fromValueArr[key.value]) setItem(fromValue, activeItem)
  fromValueArr.data = {...fromValueArr.data, ...fromValue}
  const {cardId = '', fullName = '', mobileNumber} = fromValueArr.data
  if (query && !!!(ThirdWeNeedFactor.idcard)) {
    ThirdWeNeedFactor.mobile = CounterStore.mobile
    ThirdWeNeedFactor.idcard = query.cardId
    ThirdWeNeedFactor.name = query.fullName
  }
  CardIdEmployeeInfo(cardId)
  if (cardId && fullName && mobileNumber) {
    if (cardId !== ThirdWeNeedFactor.idcard || fullName !== ThirdWeNeedFactor.name) {
      ThirdWeNeedFactor.mobile = mobileNumber
      ThirdWeNeedFactor.idcard = cardId
      ThirdWeNeedFactor.name = fullName
      if (IdCardRegularExpression(cardId) === true) {
        // checkCard(ThirdWeNeedFactor).then(res => { if (!res.success) { Toast.fail(res.message); }; buttonReslt.value = !res.success })
        buttonReslt.value = false
        // buttonReslt.value = true
      } else {
        buttonReslt.value = true
      }
    }
  }
  fromValueArr[key.value] = {...fromValue[key.value], ...fromValue}
  // insertEmployeeInfo()
}

async function CardIdEmployeeInfo(cardId) {
  if (!cardId) return
  if (cardId !== ThirdWeNeedFactor.idcard) {
    // 如果身份证号码不同 则跟换身份证号码
    // ThirdWeNeedFactor.idcard = cardId
    // 因为刷新可能改变url 中的身份证号码 所以获取
    const data = Base64.encode(JSON.stringify({cardId: cardId, fullName: ThirdWeNeedFactor.name}))
    Router.push({query: {data}})
    // if (cardId !== 1) {
    const res = await getCardIdEmployeeInfo(cardId)
    if (res.success) {
      Router.push({query: {data}})
      return new Promise(() => {
        Dialog.confirm({
          title: '提示',
          message: '是否同步上次入职信息。',
        })
            .then(() => {
              init(res.message)
              addSynEmployeeInfo({new_id: CounterStore.employeeId, old_id: res.message.employeeId})
              // on confirm
            })
            .catch(() => {
              console.log('取消')
              // on cancel
            })
      })
    }
  }

}

// 获取当前item
const getItem = function (key) {
  let it = {}
  activeList.forEach(item => {
    if (item.key === key) it = item
  })
  return it
}

watch(buttonReslt, (value) => {
  console.log(value)
})

// 切换输入模块
const active = ref('')
</script>
<style scoped>
.loading {
  margin-top: 70%;
}

.module {
  margin: 20px 0;
  padding: 0 10px;
}


::v-deep.van-tab {
  line-height: 40px;
  align-items: flex-end;
}

::v-deep.van-tabs--line .van-tabs__wrap {
  padding-top: 45px
}
</style>
